package com.gl.portal.system.controller;

import com.gl.common.constant.Constants;
import com.gl.common.enums.StatusEnum;
import com.gl.common.util.StringUtils;
import com.gl.framework.aspectj.annotation.Log;
import com.gl.framework.aspectj.enums.BusinessType;
import com.gl.framework.interceptor.annotation.RepeatSubmit;
import com.gl.framework.web.domain.TreeSelect;
import com.gl.framework.web.response.Result;
import com.gl.portal.system.service.SysDeptService;
import com.gl.portal.system.vo.SysDeptVo;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 部门信息控制器
 */
@RestController
@RequestMapping("/system/dept")
public class SysDeptController {

    @Autowired
    private SysDeptService deptService;

    /**
     * 获取部门列表
     *
     * @param filter
     * @return
     */
    @GetMapping("/list")
    @PreAuthorize("@ps.hasPermi('system:dept:list')")
    public List<SysDeptVo> list(SysDeptVo filter) {
        return deptService.selectDeptList(filter);
    }

    /**
     * 查询部门列表（排除节点）
     *
     * @param deptId
     * @return
     */
    @GetMapping("/list/exclude/{deptId}")
    @PreAuthorize("@ps.hasPermi('system:dept:list')")
    public List<SysDeptVo> excludeChild(@PathVariable(required = false) Long deptId) {
        List<SysDeptVo> depts = deptService.selectDeptList(new SysDeptVo());
        Iterator<SysDeptVo> it = depts.iterator();
        while (it.hasNext()) {
            SysDeptVo d = (SysDeptVo) it.next();
            if (d.getId().intValue() == deptId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + "")) {
                it.remove();
            }
        }
        return depts;
    }

    /**
     * 获取部门详细信息
     *
     * @param deptId
     * @return
     */
    @GetMapping("/{deptId}")
    @PreAuthorize("@ps.hasPermi('system:dept:query')")
    public SysDeptVo getInfo(@PathVariable Long deptId) {
        return deptService.selectDeptById(deptId);
    }

    /**
     * 获取部门下拉树列表
     *
     * @param vo
     * @return
     */
    @GetMapping("/treeselect")
    public List<TreeSelect> treeselect(SysDeptVo vo) {
        List<SysDeptVo> depts = deptService.selectDeptList(vo);
        return deptService.buildDeptTreeSelect(depts);
    }

    /**
     * 获取对应角色的部门列表树
     *
     * @param roleId
     * @return
     */
    @GetMapping("/role_dept_treeselect/{roleId}")
    public Map<String, Object> roleDeptTreeselect(@PathVariable Long roleId) {
        List<SysDeptVo> depts = deptService.selectDeptList(new SysDeptVo());

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        map.put("depts", deptService.buildDeptTreeSelect(depts));
        return map;
    }

    /**
     * 新增部门
     *
     * @param vo
     * @return
     */
    @RepeatSubmit
    @PostMapping
    @PreAuthorize("@ps.hasPermi('system:dept:add')")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    public Result add(@Validated @RequestBody SysDeptVo vo) {
        if (Constants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(vo))) {
            return Result.fail(  "新增部门'" + vo.getDeptName() + "'失败，部门名称已存在");
        }

        deptService.saveDept(vo);
        return Result.success();
    }

    /**
     * 修改部门
     *
     * @param vo
     * @return
     */
    @PutMapping
    @PreAuthorize("@ps.hasPermi('system:dept:edit')")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    public Result edit(@Validated @RequestBody SysDeptVo vo) {
        if (Constants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(vo))) {
            return Result.fail( "修改部门'" + vo.getDeptName() + "'失败，部门名称已存在");
        } else if (vo.getParentId().equals(vo.getId())) {
            return Result.fail( "修改部门'" + vo.getDeptName() + "'失败，上级部门不能是自己");
        } else if (StatusEnum.DISABLE.value() == vo.getStatus()
                && deptService.selectNormalChildrenDeptById(vo.getId()) > 0) {
            return Result.fail( "该部门包含未停用的子部门！");
        }

        deptService.updateDept(vo);
        return Result.success();
    }

    /**
     * 删除部门
     *
     * @param deptId
     * @return
     */
    @DeleteMapping("/{deptId}")
    @PreAuthorize("@ps.hasPermi('system:dept:remove')")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    public Result remove(@PathVariable Long deptId) {
        if (deptService.hasChildByDeptId(deptId)) {
            return Result.fail( "存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return Result.fail( "部门存在用户,不允许删除");
        }

        deptService.deleteDeptById(deptId);
        return Result.success();
    }
}
